package com.zhuiYun.project.config.jwt;

import com.zhuiYun.project.common.errorCode.CommonException;
import com.zhuiYun.project.common.response.CommonResult;
import com.zhuiYun.project.common.response.ResponseUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName ExceptionHandlerFilter
 * @Description 捕获token异常
 * @Author zcy
 * @Date 2023/3/28 9:26
 **/
@Component
public class ExceptionHandlerFilter extends OncePerRequestFilter {
    /**
     * 处理捕获的异常
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            filterChain.doFilter(request, response);
        } catch (Exception ex) {
            Map<String, Object> responseData = new HashMap<>();
            // 判断如果时自定异常则抛出自定义异常 否则封装后抛出
            if (ex instanceof CommonException) {
                CommonException commonException = (CommonException) ex;
                responseData.put("errMsg", commonException.getErrMsg());
                responseData.put("errCode", commonException.getErrCode());
            } else {
                responseData.put("errMsg", ex.toString());
                responseData.put("errCode", ex.getStackTrace());
            }
            ResponseUtil.responseJson(response, CommonResult.error(responseData));
        }
    }
}
